/**
 * Copyright 2020 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.dbfly.util.dtd;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;

import com.jianggujin.dbfly.util.JAssert;
import com.jianggujin.dbfly.util.JStringUtils;

/**
 * DTD配置实体
 * 
 * @author jianggujin
 *
 */
public class JDTD implements JDTDOutput {
    private Map<String, JDTDElement> elements = new LinkedHashMap<>();

    @Override
    public void write(PrintWriter out) throws IOException {
        out.println("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
        for (JDTDElement item : this.elements.values()) {
            item.write(out);
        }
        out.flush();
    }

    /**
     * 添加元素
     * 
     * @param elements
     */
    public void add(JDTDElement... elements) {
        for (JDTDElement element : elements) {
            JAssert.notNull(element, "elements中不能包含空元素");
            JAssert.isTrue(!this.elements.containsKey(element.getName()),
                    JStringUtils.format("元素[{}]已经存在", element.getName()));
            this.elements.put(element.getName(), element);
        }
    }

    /**
     * 是否包含指定名称元素
     * 
     * @param name
     * @return
     */
    public boolean has(String name) {
        return this.elements.containsKey(name);
    }

    /**
     * 移除指定名称元素
     * 
     * @param name
     * @return
     */
    public JDTDElement remove(String name) {
        JDTDElement element = this.elements.remove(name);
        JAssert.notNull(element, JStringUtils.format("元素[{}]不存在", name));
        return element;
    }

    /**
     * 获取指定名称元素
     * 
     * @param name
     * @return
     */
    public JDTDElement get(String name) {
        JDTDElement element = this.elements.get(name);
        JAssert.notNull(element, JStringUtils.format("元素[{}]不存在", name));
        return element;
    }
}
